package com.example.demo.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: xumf
 * @Date: 2019/7/16 16:07
 */
@Slf4j
public class TimeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime=System.currentTimeMillis();
        request.setAttribute("startTime",startTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        long startTime = (Long)request.getAttribute("startTime");
        long endTime=System.currentTimeMillis();
        long executeTime=endTime-startTime;

        log.warn("执行{}类的{}方法，花费了：{}",
                handlerMethod.getBean().getClass().getSimpleName(),handlerMethod.getMethod().getName(),executeTime);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        log.warn("【*** TimeInterceptor.afterCompletion() ***】" + handlerMethod.getBean().getClass().getSimpleName());
    }
}
